//============================================================================
// NativeBuffer.cs
//
// Copyright (c) 2005-2006 U.S. TrailMaps, LLC
// THIS MATERIAL IS CONFIDENTIAL AND PROPRIETARY TO U.S. TRAILMAPS AND
// MAY NOT BE REPRODUCED, PUBLISHED OR DISCLOSED TO OTHERS WITHOUT COMPANY
// AUTHORIZATION.
//
// This work is derived from Waymex GPS Library for .Net version 2.7.9 source.
// Portions copyright (c) 2004-2005 Waymex IT Ltd
//============================================================================

using System;
using System.Runtime.InteropServices;

namespace Waymex.Gps.Garmin.Usb
{
	/// <summary>
	/// A data buffer that can be used by native code.
	/// </summary>
	/// <remarks>
	/// The memory is allocated from the unmanaged memory of the process using GlobalAlloc.
	/// </remarks>
	internal class NativeBuffer : IDisposable
	{
		private int size;
		public int Size
		{
			get { return size; }
		}

		private IntPtr pointer;
		public IntPtr Pointer
		{
			get { return pointer; }
		}

		public NativeBuffer(int size)
		{
			this.size = size;
			this.pointer = Marshal.AllocHGlobal(size);
		}

		~NativeBuffer()
		{
			Dispose(false);
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		private void Dispose(bool disposing)
		{
			if (pointer != IntPtr.Zero)
			{
				Marshal.FreeHGlobal(pointer);
				pointer = IntPtr.Zero;
				size = 0;
			}
		}
	}
}
